<template>
	<view class="container-bottom">
		<camera v-if="cameraOn" device-position="back" flash="off" binderror="cameraError"
			style="width: 100vw; height: 100vh; position: fixed; top: 0; left: 0; z-index: 1000;"></camera>
		<view v-if="cameraOn && showButtons"
			style="position: absolute;  bottom: 80px; left: 50%; transform: translateX(-50%); z-index: 1001;">
			<button type="primary" @click="startCamera" class="camera-button">
			</button>
		</view>
		<view v-if="cameraOn && showButtons" @click="showIndex"
			style="position: absolute; bottom: 80px; right: 20px; z-index: 1001;">
			<image style="width: 50px;height: 65px;" src="@/static/images/quxiao.png"></image>
			<!-- <button @click="cameraOn = false;showButtons = false">取消</button> -->
		</view>
	</view>
</template>

<script>
	import {
		toLogin
	} from '@/libs/login.js';
	import {
		getMd5Token,
		vinCode,
		getCountVin,
		searchCarDetail,
		getBrandModel,
	} from '@/api/car.js';
	import {
		saveVinLog,
	} from '@/api/common.js';
	import {
		HTTP_REQUEST_URL,
	} from '@/config/app';
	import {
		mapGetters
	} from "vuex";
	export default {
		data() {
			return {
				showButtons: true,
				cameraOn: true, // 控制相机组件的显示与隐藏
				vinCodeCount: 0, //用户提供的有效车架号
				vinCode: '', //车架号
				isRecording: false, // 录音状态
				isListening: false, //监听状态
				token: '',
				imagePath: '', // 图片路径
				isDrawing: false,
				toView: '',
				keyword: '',
				vin: '',
				modelDetail: '',
				brand: '',
				series: '',
				modelYear: '',
				model: '',
				modelId: '',
				salesVersion: '',
				cc: '',
				factory: '',
				carInfo: [],
				img: '',
			}
		},
		computed: {
			...mapGetters({
				isLogin: 'isLogin',
				uid: 'uid',
			})
		},
		methods: {
			showIndex() {
				uni.navigateBack({
					delta: 1 // 返回的页面数，如果不填默认为1，表示返回上一级页面
				});
			},
			startCamera() {
				if (this.isLogin == false) {
					toLogin();
					return;
				}
				// 创建相机上下文
				const ctx = uni.createCameraContext();
				// 拍照
				ctx.takePhoto({
					quality: 'high', // 拍照质量
					success: (res) => {
						// 获取图片路径
						const filePath = res.tempImagePath;
						console.log('拍摄成功，图片路径:', filePath);
						// 压缩图片
						uni.compressImage({
							src: filePath,
							quality: 80, // 质量 80%
							success: (compressRes) => {
								const compressedPath = compressRes.tempFilePath;
								// 上传图片文件
								this.uploadImage(compressedPath); // 上传压缩后的图片文件
							},
							fail: (err) => {
								uni.showToast({
									title: '图片压缩失败',
									icon: 'none',
								});
							}
						});
					},
					fail: (err) => {
						console.error('拍摄失败:', err);
						uni.showToast({
							title: '拍摄失败',
							icon: 'none',
						});
					}
				});
			},
			// 上传图片文件
			uploadImage(filePath) {
				// 显示加载提示
				uni.showLoading({
					title: '处理中...',
					mask: true, // 遮罩层，防止用户点击其他区域
				});
				uni.uploadFile({
					url: HTTP_REQUEST_URL + '/api/car/getMd5Token',
					//url: 'http://localhost:8930/car/getMd5Token',
					filePath: filePath,
					name: 'file', // 参数名，后端获取的字段
					success: (uploadRes) => {
						console.log('上传成功:', uploadRes.data);
						// 如果后端返回的字符串是 JSON 格式，尝试解析
						try {
							const parsedData = JSON.parse(uploadRes.data);
							console.log(parsedData)
							this.callVinApi(parsedData); // 将解析后的数据传递给下一个函数
						} catch (error) {
							console.error("JSON 解析失败:", error);
						}
					},
					fail: (err) => {
						console.error('未识别到有效信息:', err);
						uni.showToast({
							title: '未识别到有效信息，请重试',
							icon: 'none',
						});
					},
					complete: () => {
						console.log(this.modelDetail);
						// 无论请求成功或失败，都隐藏加载提示
						uni.hideLoading();
					}
				});
			},
			// 根据返回内容查询
			callVinApi(uploadResponse) {
				// 判断 uploadResponse 和 uploadResponse.value 是否为 null 或 undefined
				if (!uploadResponse || !uploadResponse.value) {
					uni.showToast({
						title: '数据为空',
						icon: 'none',
					});
					return; // 如果上传响应数据不合法，直接返回，不继续执行后面的逻辑
				}
				const {
					brand,
					series,
					modelDetail,
					Model,
					vin,
					modelYear,
					salesVersion,
					cc,
					factory,
					img,
				} = uploadResponse.value;
				// 连接品牌和系列
				const brandModel = `${factory}${Model}`;

				this.modelDetail = `${modelDetail}`;
				this.vin = `${vin}`;
				this.brand = `${brand}`
				this.series = `${series}`
				this.model = `${Model}`
				this.modelYear = `${modelYear}`
				this.salesVersion = `${salesVersion}`
				this.cc = `${cc}`
				this.factory = `${factory}`
				this.img = `${img}`

				this.keyword = this.modelDetail;
				console.log("搜索条件：" + brandModel)
				this.getSearchKeyAndBrand(brandModel, brand)
					.then(() => {
						if (this.searchList.length > 0) { // 确保 searchList 被正确赋值后判断
							this.saveVinLog("正常查询");
						}
					})
					.catch(error => {
						console.error("获取搜索数据失败:", error);
						this.saveVinLog("未查询到内容");
					});
				// this.searchType = 'vin'; //搜索方式设定
				this.vinCode = this.vin
			},
			getSearchKeyAndBrand(keyword, brand) {
				this.searchType = "other";
				return new Promise((resolve, reject) => {
					this.searchList = [];
					this.$request.get("car/getKeyAndBrand", {
						keyWord: keyword,
						brand: brand,
					}).then(res => {
						this.searchList = res.value;
						resolve(res); // 确保在获取数据后执行后续逻辑
					}).catch(err => {
						this.$util.Tips({
							title: err
						});
						reject(err); // 请求失败时拒绝
					});
				});
			},
			saveVinLog(message) {
				// 存入vin码日志
				saveVinLog({
					userId: this.uid || '', // 确保 userId 不为空
					vin: this.vin,
					type: message,
					brand: this.brand,
					series: this.series,
					model: this.model,
					modelYear: this.modelYear,
					modelDetail: this.modelDetail,
					salesVersion: this.salesVersion,
					cc: this.cc,
					factory: this.factory,
					img: this.img,
				}).then(res => {
					this.img = res.value.img;
					console.log("保存后返回的图片" + res.value.img)
					this.searchCarDetail();
				});
				this.getCountVin(); // 计数（该用户有效vin码记录）
			},
			async searchCarDetail() {
				this.showDetail = false;
				try {
					// 查具体信息 wxCar 表内容
					const res = await searchCarDetail({
						factory: this.factory,
						model: this.model,
						modelYear: this.modelYear,
						salesVersion: this.salesVersion,
						cc: this.cc,
						brand: this.brand,
						userId: this.uid
					});
					console.log(this.model);
					if (res.value != null) {
						this.carInfo = res.value;
						console.log("有具体车型：" + res.value.carId);
						// 判断字段是否为空、null 或 undefined
						uni.setStorageSync('carInfo', this.carInfo)
						uni.reLaunch({
							url: `/pages/index/index?showDetail=true&keyword=` + this.keyword + '&vin=' + this.vinCode,
						});
					} else {
						this.carInfo = [];
						// 提示暂无信息
						console.log("无具体车型：" + this.modelDetail);
					}
				} catch (error) {
					console.error("查询具体车型失败：", error);
					// 可选：捕获错误并提示
					uni.showToast({
						title: '查询失败，请稍后重试',
						icon: 'none',
						duration: 2000
					});
				}
			},
			getCountVin() { //获取该用户上传有效车架号信息
				getCountVin({
						userId: this.uid ? this.uid : '',
					}).then(res => {
						// 处理成功的响应
						if (res && res.value) {
							this.vinCodeCount = res.value.length
						} else {
							console.log('无数据');
						}
					})
					.catch(error => {
						uni.showToast({
							title: '获取有效车架号错误',
							icon: 'none',
						});
					});
			},
		}
	}
</script>

<style>
	.container-bottom {
		position: fixed;
		bottom: 0px;
		margin-top: 10rpx;
		width: 100%;
	}

	.camera-button {
		width: 160rpx;
		/* 按钮直径 */
		height: 160rpx;
		/* 按钮直径 */
		background-color: #00a128;
		/* 按钮颜色 */
		border-radius: 50%;
		/* 使按钮呈圆形 */
		border: 2px solid #ffffff;
		/* 添加白色边框，类似微信的样式 */
		box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
		/* 添加阴影效果 */
	}
</style>